<template>
  <div class='container'>
    <el-card class="box-card" shadow="never">
      <!-- 搜索 -->
      <el-form>
        <div class="filter-container">
          <el-col :span="8">
            <el-form-item label="目录名称">
              <el-input v-model="search.directoryName" style="width: 234px;" class="filter-item"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态">
              <el-select style="width: 254px;" placeholder="请选择" v-model.trim="search.state" clearable filterable>
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span='4'>
            <el-button @click="handleClear">清除</el-button>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </el-col>
          <el-col :span="4">
            <el-button class="filter-item fr" size="small" style="margin-left: 10px;" type="success" icon="el-icon-edit" @click="dialogVisible = true">新增目录</el-button>
          </el-col>
        </div>
      </el-form>
      <!-- 数据记录 -->
      <el-alert :title="alertText" type="info" class="alert" :closable="false" show-icon></el-alert>
      <!-- 数据列表 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column align="center" label="序号" type="index" :index="handleIndex">

        </el-table-column>
        <el-table-column align="center" label="所属学科">
          <template v-slot={row}>
            <span>{{row.subjectName}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="目录名称">
          <template v-slot={row}>
            <span>{{row.directoryName}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建者" :formatter="formatManager">
        </el-table-column>
        <el-table-column align="center" label="创建日期" :formatter="formatDate">
        </el-table-column>
        <el-table-column align="center" label="面试题数量">
          <template v-slot={row}>
            <span>{{row. totals}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态" :formatter="formatType">
        </el-table-column>
        <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
          <template v-slot={row}>
            <el-button class="button" type="text" @click="handleStatus(row)">
              <span v-if="row.state===0">启用</span>
              <span v-else>禁用</span>
            </el-button>
            <el-button type="text" :disabled="row.state===0 ?false:true" @click="handleEdit(row)">
              修改
            </el-button>
            <el-button type="text" :disabled="row.state===0 ?false:true" @click="handleDel(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <div class="pages">
          <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="Number(requestParameters.page)" :total="Number(total)" :page-size="Number(requestParameters.pagesize)" :page-sizes="[5,10,20,30]" layout="->,sizes, prev, pager, next, jumper"></el-pagination>
        </div>
      </div>
    </el-card>

    <!-- 新增标签的弹窗 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleClose">
      <el-form ref="addRef" :model="rulesForm" style="width: 90%;" label-position="left" label-width="150px" :rules="rules">
        <el-form-item label="所属学科:" prop="subjectID">
          <el-select placeholder="请选择" v-model="rulesForm.subjectID">
            <el-option v-for="item in subjects" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <!-- <el-input placeholder="请输入所属学科" v-model="rulesForm.subjectName"></el-input> -->
        </el-form-item>
        <el-form-item label="目录名称:" prop="directoryName">
          <el-input placeholder="请输入目录名称" v-model="rulesForm.directoryName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/subjects'
import { list, detail, update, remove, changeState, add } from '../../api/hmmm/directorys'
import moment from 'moment'
import { status, manager } from '../../api/hmmm/constants'
export default {
  data () {
    return {
      // 学科
      subjects: [],
      // 新增标签弹窗标志位
      dialogVisible: false,
      // 表单内容
      rulesForm: {
        subjectName: '',
        directoryName: '',
        subjectID: ''
      },
      // 表单验证规则
      rules: {
        subjectName: [{
          required: true, message: '请输入所属学科', trigger: ['blur', 'change']
        }],
        directoryName: [
          { required: true, message: '请输入目录名称', trigger: ['blur', 'change'] }
        ]
      },
      search: {
        directoryName: '',
        state: ''
      },
      // select选择器
      options: [{
        value: 1,
        label: '启用'
      }, {
        value: 0,
        label: '禁用'
      }],
      // 分页数据
      requestParameters: {
        page: 1,
        pagesize: 10
      },
      tableData: [],
      // 提示文本消息
      alertText: '',
      // 总条数
      total: ''
    }
  },
  computed: {
    title () {
      return this.rulesForm.id ? '修改文章' : '添加文章'
    }
  },
  methods: {
    async loadFormList () {
      const ret = await simple()
      this.subjects = ret.data
    },
    // 功能:删除
    async handleDel (row) {
      const ret = await this.$confirm('确认删除吗?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (ret === 'cancel') return
      try {
        const retDel = await remove(row)
        // console.log(id)
        // console.log(retDel)
        if (retDel.status === 200) {
          // 删除成功，刷新列表
          this.$message.success('删除成功')
          this.loadArtList()
        } else {
          this.$message.error('删除失败')
        }
      } catch {
        this.$message.error('删除失败')
      }
    },
    // 功能:提交表单(新增+修改)
    handleSubmit () {
      this.$refs.addRef.validate(async valid => {
        if (!valid) return
        // 验证通过 调用接口 刷新列表 关闭弹窗 清空表单
        if (this.rulesForm.id) {
          // 编辑
          try {
            const ret = await update(this.rulesForm)
            // console.log(ret)
            if (ret.status === 200) {
              this.loadArtList()
              this.$message.success('修改成功')
              this.dialogVisible = false
              this.$refs.addRef.resetFields()
              this.rulesForm = this.$options.data().rulesForm
            } else {
              this.$message.error('修改失败')
            }
          } catch {
            this.$message.error('修改失败')
          }
        } else {
          try {
            // 添加
            const ret = await add(this.rulesForm)
            if (ret.status === 200) {
              this.loadArtList()
              this.$message.success('添加成功')
              this.dialogVisible = false
              this.$refs.addRef.resetFields()
            } else {
              this.$message.error('添加失败')
            }
          } catch {
            this.$message.error('添加失败')
          }
        }
      })
    },
    // 功能:关闭弹窗
    handleClose () {
      // 弹窗关闭；清空表单；清空表单验证规则
      this.dialogVisible = false
      this.$refs.addRef.resetFields()
      // 清除表单内容（编辑权限的id）
      this.rulesForm = this.$options.data().rulesForm
    },
    // 功能:修改
    async handleEdit (row) {
      const ret = await detail(row)
      if (ret.status === 200) {
        this.rulesForm = ret.data
        this.dialogVisible = true
      }
      // console.log(ret)
    },
    // 功能：加载数据列表
    async loadArtList (params) {
      try {
        this.loading = true
        const ret = await list(this.requestParameters)
        if (ret.status === 200) {
          // 调用接口成功
          console.log(ret)
          this.tableData = ret.data.items
          this.total = ret.data.counts
          this.alertText = `共 ${this.total} 条记录`
        } else {
          this.$message.error('加载文章列表失败')
        }
      } catch {
        this.$message.error('加载文章列表失败')
      } finally {
        this.loading = false
      }
    },
    // 功能:搜索
    async handleSearch () {
      if (this.search.directoryName === '' || this.search.state === '') {
        this.loadArtList()
      } else {
        const ret = await list({
          ...this.requestParameters,
          ...this.search
        })
        // console.log(ret)
        if (ret.status === 200) {
          this.tableData = ret.data.items
          this.total = ret.data.counts
          this.alertText = `共 ${this.total} 条记录`
        }
      }
    },
    // 功能：点击清除按钮，清除输入框中的内容
    handleClear () {
      this.search.keyword = ''
      this.search.state = ''
      this.loadArtList()
    },
    // 功能：启用禁用
    handleStatus (row) {
      if (row.state === 1) {
        row.state = 0
      } else {
        row.state = 1
      }
      // 文章状态
      changeState({
        id: row.id,
        state: row.state
      })
    },
    // 功能：分页
    //  每页显示信息条数
    handleSizeChange (val) {
      this.requestParameters.pagesize = val
      if (this.requestParameters.page === 1) {
        this.loadArtList(this.requestParameters)
      }
    },
    //  进入某一页
    handleCurrentChange (val) {
      this.requestParameters.page = val
      this.loadArtList()
    },
    //  动态索引序号
    handleIndex (index) {
      const { page, pagesize } = this.requestParameters
      return (page - 1) * pagesize + index + 1
    },
    // 功能：格式化时间
    formatDate (date) {
      // console.log(date)
      if (!date.addDate) return ''
      return moment(date.addDate).format('YYYY-MM-DD hh:mm:ss')
    },
    // 功能:格式化状态形式
    formatType (row) {
      const info = status.find(item => parseInt(item.value) === parseInt(row.state))
      if (info) {
        return info.label
      } else {
        return '其他'
      }
    },
    formatManager (row) {
      const info = manager.find(item => parseInt(item.value) === parseInt(row.creatorID))
      if (info) {
        return info.label
      } else {
        return '其他'
      }
    }
  },
  created () {
    this.loadArtList()
    this.loadFormList()
  }

}
</script>

<style scoped lang='less'>
.button {
  margin-right: 15px;
}
</style>
